﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Tasks.Common;
using Tasks.Business;
using Tasks.Common.Entitys;
using MyLib.Util;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Web.Caching;

namespace Tasks.Core
{
    /// <summary>
    /// 配置类
    /// </summary>
    public class Config
    {
        /// <summary>
        /// 登录
        /// resultno: 1 成功  2 账号或密码错误
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static ExecuteResult Login(string account, string password)
        {
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
                return new ExecuteResult() { ResultNo = 2, Message = "账号或密码错误！" }; ;

            AccountBLL accountBLL = new AccountBLL();
            Account acc = accountBLL.GetAccountByAccountNo(account);

            password = SecurityUtil.EncryptToMD5(password);
            if (acc == null ||
                (acc.UserType != (int)UserType.Employee && acc.UserType != (int)UserType.Enterprise))
            {
                return new ExecuteResult() { ResultNo = 2, Message = "账号有误!" };
            }

            if (acc != null && acc.Password == password)
            {
                Operator opt = new Operator();
                opt.UserID = acc.UserID;
                opt.Name = acc.Name;

                if (acc.UserType == (int)UserType.Enterprise) //企业会员，企业会员的上级为
                {
                    //企业会员登录
                    EnterpriseMember ent = accountBLL.GetEnterpriseMember(acc.UserID);
                    //Account preEnt = accountBLL.GetEnterpriseMember(acc.OwnerID);

                    if (ent.EnterpriseMemberState != (int)EnterpriseMemberState.有效)
                        return new ExecuteResult() { ResultNo = 2, Message = "账号无效" };
                    if (ent.IsDistribution == 0)
                        return new ExecuteResult() { ResultNo = 2, Message = "您还没开通分销权限" };
                    opt.CompanyID = acc.UserID;
                    opt.CompanyName = acc.Name;
                    opt.MobileNo = acc.MobileNo;
                    opt.ParentCompanyID = acc.OwnerID;
                    //opt.ParentCompanyName = preEnt.Name;
                }
                else if (acc.UserType == (int)UserType.Employee) //员工
                {

                    Employee emp = accountBLL.GetEmployee(acc.UserID);
                    EnterpriseMember ent = accountBLL.GetEnterpriseMember(acc.OwnerID);
                    if (emp.EmployeeState != (int)EmployeeState.有效 || ent.EnterpriseMemberState != (int)EnterpriseMemberState.有效)
                        return new ExecuteResult() { ResultNo = 2, Message = "账号无效" };


                    opt.CompanyID = acc.OwnerID;
                    opt.CompanyName = ent.Name;
                    opt.MobileNo = ent.MobileNo;
                    opt.ParentCompanyID = ent.OwnerID; //所属公司的上级

                    //Account preEnt = accountBLL.GetEnterpriseMember(ent.OwnerID);
                    //opt.Name = preEnt.Name;
                }

                Config.CurrentOperator = opt;
                acc.LastLoginTime = DateTime.Now;

                accountBLL.ModifyAccount(acc);

                return new ExecuteResult() { ResultNo = 1, Message = "登录成功" };
            }
            return new ExecuteResult() { ResultNo = 2, Message = "账号或密码错误！" }; ;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void Logout()
        {
            Config.CurrentOperator = null;
            HttpContext.Current.Session.Clear();
        }

        /// <summary>
        /// 当前操作者
        /// </summary>
        public static Operator CurrentOperator
        {
            get
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies["Operator"];

                if (cookie == null || !cookie.HasKeys)
                    return null;
                else
                {
                    return new Operator
                    {
                        Name = HttpUtility.UrlDecode(cookie["Name"]),
                        UserID = int.Parse(cookie["UserID"]),
                        CompanyID = int.Parse(cookie["CompanyID"]),
                        CompanyName = HttpUtility.UrlDecode(cookie["CompanyName"]),
                        MobileNo = HttpUtility.UrlDecode(cookie["MobileNo"]),
                        CompanyCategoryID = int.Parse(cookie["CompanyCategoryID"]),
                        ParentCompanyID = int.Parse(cookie["ParentCompanyID"]),
                        ParentCompanyName = HttpUtility.UrlDecode(cookie["ParentCompanyName"])
                    };
                }
            }
            set
            {
                if (value == null)
                {
                    HttpCookie cookie1 = HttpContext.Current.Response.Cookies["Operator"];
                    cookie1.Expires = DateTime.Now.AddDays(-100);
                    HttpContext.Current.Response.SetCookie(cookie1);

                    return;
                }

                HttpCookie cookie = HttpContext.Current.Response.Cookies["Operator"];
                cookie["Name"] = HttpUtility.UrlEncode(value.Name);
                cookie["UserID"] = value.UserID.ToString();
                cookie["CompanyID"] = value.CompanyID.ToString();
                cookie["CompanyName"] = HttpUtility.UrlEncode(value.CompanyName);
                cookie["MobileNo"] = HttpUtility.UrlEncode(value.MobileNo);
                cookie["ParentCompanyName"] = HttpUtility.UrlEncode(value.ParentCompanyName);
                cookie["CompanyCategoryID"] = value.CompanyCategoryID.ToString();
                cookie["ParentCompanyID"] = value.ParentCompanyID.ToString();
                cookie.HttpOnly = false;

                //System.Text.Encoding.
                HttpContext.Current.Response.SetCookie(cookie);
            }
        }

        /// <summary>
        /// 景点门票编号 
        /// </summary>
        public static IList<Mapping> eTicketMapping
        {
            get
            {
                IList<Mapping> sceneryMapping = (IList<Mapping>)HttpContext.Current.Cache["eTicketMapping"];
                if (sceneryMapping == null || sceneryMapping.Count == 0)
                {
                    sceneryMapping = new List<Mapping>();
                    XmlDocument xmlDoc = new XmlDocument();
                    //xmlDoc.Load(HttpContext.Current.Server.MapPath("/Config/eTicketMapping.xml"));
                    xmlDoc.Load(HttpContext.Current.Server.MapPath("~/bin/Config//eTicketMapping.xml"));
                    XmlNodeList nodeList = xmlDoc.SelectNodes("/SceeneryMapping/Scenery");
                    foreach (XmlNode node in nodeList)
                    {
                        Mapping scenery = new Mapping();
                        scenery.OriginalNo = node.Attributes["SceneryNo"].Value;
                        scenery.MappingNo = node.Attributes["MappingSceneryNo"].Value;
                        XmlNodeList ticketNodeList = xmlDoc.SelectNodes("/SceeneryMapping/Scenery/SceneryTicket");
                        scenery.ClientMappings = new List<Mapping>();

                        foreach (XmlNode n in ticketNodeList)
                        {
                            Mapping ticket = new Mapping();
                            ticket.OriginalNo = n.Attributes["TicketNo"].Value;
                            ticket.MappingNo = n.Attributes["MapTicketNo"].Value;
                            scenery.ClientMappings.Add(ticket);
                        }
                        sceneryMapping.Add(scenery);
                    }
                    HttpContext.Current.Cache.Insert("eTicketMapping", sceneryMapping);
                    return sceneryMapping;
                }
                else
                {
                    return sceneryMapping;
                }
            }

        }
        /// <summary>
        /// 通过编号获取映射对象
        /// </summary>
        /// <param name="sceneryNo"></param>
        /// <returns></returns>
        public static Mapping GetMapping(string sceneryNo)
        {
            IList<Mapping> mapSceneryList = Config.eTicketMapping;
            Mapping mapScenery = mapSceneryList.FirstOrDefault(t => t.OriginalNo == sceneryNo);
            return mapScenery;
        }

        /// <summary>
        /// 上传文件密钥
        /// </summary>
        public static string UploadKey
        {
            get
            {
                return ConfigurationManager.AppSettings["UploadKey"];
            }
        }

        /// <summary>
        /// 系统皮肤
        /// </summary>
        public static string SystemTheme
        {
            get
            {
                return ConfigurationManager.AppSettings["theme"];
            }
        }

        public static string ImageURL
        {
            get
            {
                return ConfigurationManager.AppSettings["imageURL"];
            }
        }

        public static int GetTicketGroupActiveDay
        {
            get
            {
                return Convert.ToInt32(ConfigurationManager.AppSettings["TicketGroupActiveDay"]);
            }
        }

        /// <summary>
        /// 获取css文件路径
        /// </summary>
        /// <param name="cssName"></param>
        /// <returns></returns>
        public static string GetCssResourcePath(string cssName)
        {
            return "/themes/" + Config.SystemTheme + "/" + cssName;
        }

        /// <summary>
        /// 获取css文件路径
        /// </summary>
        /// <param name="cssName"></param>
        /// <returns></returns>
        public static string GetResourceUrl(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return "";
            }
            return "/uploads/" + filePath.TrimStart('/');
        }

        /// <summary>
        /// 当前执行的所属公司
        /// </summary>
        public static int CompanyID
        {
            get { return CurrentOperator.CompanyID; }
        }

        /// <summary>
        /// 当前执行的所属公司
        /// </summary>
        public static int ParentCompanyID
        {
            get { return CurrentOperator.ParentCompanyID; }
        }

        /// <summary>
        /// 线路缩略图尺寸
        /// </summary>
        public static string[] TourThumbnailSize
        {
            get
            {
                string str = GetConfigForDict(DictConfig.SITE_GLOBAL_SET, "线路缩略图");
                if (string.IsNullOrEmpty(str))
                    return new string[] { "100x100" };
                else
                    return str.Split(',');
            }
        }

        /// <summary>
        /// 景点缩略图尺寸
        /// </summary>
        public static string[] SceneryThumbnailSize
        {
            get
            {
                string str = GetConfigForDict(DictConfig.SITE_GLOBAL_SET, "景点缩略图");
                if (string.IsNullOrEmpty(str))
                    return new string[] { "100x100" };
                else
                    return str.Split(',');
            }
        }

        /// <summary>
        /// 酒店缩略图尺寸
        /// </summary>
        public static string[] HotelThumbnailSize
        {
            get
            {
                string str = GetConfigForDict(DictConfig.SITE_GLOBAL_SET, "酒店缩略图");
                if (string.IsNullOrEmpty(str))
                    return new string[] { "100x100" };
                else
                    return str.Split(',');
            }
        }

        /// <summary>
        /// 获取缩略图URL
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetThumbnailUrl(string fileName, int index)
        {
            string url = "/uploads/" + Path.GetFileNameWithoutExtension(fileName) + "_" + index + Path.GetExtension(fileName);
            return url;
        }

        /// <summary>
        /// 获取缩略图URL
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetFileUrl(string fileName)
        {
            string url = "/uploads/" + fileName;
            return url;
        }

        /// <summary>
        /// 文件上传路径
        /// </summary>
        public static string UploadPath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory + "uploads\\";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public static string MailHost
        {
            get
            {
                return ConfigurationManager.AppSettings["mailHost"];
            }
        }
        public static string mailPassword
        {
            get
            {
                return ConfigurationManager.AppSettings["mailPassword"];
            }
        }

        /// <summary>
        /// API通知回调地址
        /// </summary>
        public static string apiNoticeUrl
        {
            get
            {
                return ConfigurationManager.AppSettings["apiNoticUrl"];
            }
        }
        /// <summary>
        /// 在字典里获取配置信息(没有缓存配置数据，需要重写 hexw)
        /// </summary>
        /// <param name="dictkey"></param>
        /// <param name="dictName"></param>
        /// <returns></returns>
        public static string GetConfigForDict(string dictkey, string dictName)
        {
            if (string.IsNullOrWhiteSpace(GetConfigForDict(dictkey, dictName, CompanyID)))
            {
                return GetConfigForDict(dictkey, dictName, 205);
            }
            else
            {
                return GetConfigForDict(dictkey, dictName, CompanyID);
            }
        }

        /// <summary>
        /// 在字典里获取配置信息(没有缓存配置数据，需要重写 hexw)
        /// </summary>
        /// <param name="dictkey"></param>
        /// <param name="dictName"></param>
        /// <returns></returns>
        public static string GetConfigForDict(string dictkey, string dictName, int ownerID)
        {
            BasedataBLL baseBLL = new BasedataBLL(ownerID);
            IList<DictValue> dicts = baseBLL.GetDicts(dictkey);
            DictValue dict = dicts.FirstOrDefault(t => t.Name == dictName);
            //如果没有字典值，则在数据库中新增一条记录
            if (dict == null)
            {
                IList<DictValue> dicts2 = baseBLL.GetDicts(dictkey, Config.AdminID);
                DictValue dictDefault = dicts2.FirstOrDefault(t => t.Name == dictName);
                dict = new DictValue()
                {
                    DictKey = dictDefault.DictKey,
                    Name = dictDefault.Name,
                    Content = dictDefault.Content,
                    OwnerID = ownerID,
                    State = 1,
                    IsLock = 0,
                    ParentID = 0,
                    SNO = 99
                };
                baseBLL.CreateDict(dict);
            }

            //这里需要缓存

            return dict == null ? "" : dict.Content;
        }

        /// <summary>
        /// 当前操作页面的绝对路径
        /// </summary>
        public static string AbsoluteUri
        {
            get
            {
                string url = HttpContext.Current.Request.Url.AbsoluteUri;
                if (Config.IsLoadBalancing && !HttpContext.Current.Request.Url.IsDefaultPort)  //使用负载均衡模式，采用顶级域名模式，过滤端口
                {
                    url = url.Replace(":" + HttpContext.Current.Request.Url.Port, "");
                }

                return url;
            }
        }


        #region "系统全局配置"

        /// <summary>
        /// 临时系统私钥，对各种数据加密使用
        /// </summary>
        public static string SystemName
        {
            get
            {
                string value = ReadConfigKey("system_name");
                return string.IsNullOrEmpty(value) ? "自游天下网络科技有限公司" : value;
            }
        }

        /// <summary>
        /// 临时系统私钥，对各种数据加密使用
        /// </summary>
        public static string PrivateKey
        {
            get
            {
                string value = ReadConfigKey("private_key");
                return string.IsNullOrEmpty(value) ? "ljsdj@#@#$%$;ksdf" : value;
            }
        }

        /// <summary>
        /// 管理公司ID，（企业ID，最大权限）
        /// </summary>
        public static int AdminID
        {
            get
            {
                string value = ReadConfigKey("adminID");
                return string.IsNullOrEmpty(value) ? 0 : int.Parse(value);
            }
            set
            {
                WriteConfigKey("adminID", value.ToString());
            }
        }

        /// <summary>
        /// 企业数据模板UserID
        /// </summary>
        public static int DataTemplateID
        {
            get
            {
                string value = ReadConfigKey("dataTemplateID");
                return string.IsNullOrEmpty(value) ? 0 : int.Parse(value);
            }
            set
            {
                WriteConfigKey("dataTemplateID", value.ToString());
            }
        }

        /// <summary>
        /// 系统是否已完成安装
        /// </summary>
        public static bool Installed
        {
            get
            {
                string value = ReadConfigKey("installed");
                return value == "1";
            }
            set
            {
                WriteConfigKey("installed", Installed ? "1" : "0");
            }
        }

        /// <summary>
        /// 系统是否启用负载均衡
        /// </summary>
        public static bool IsLoadBalancing
        {
            get
            {
                string value = ReadConfigKey("is_load_balancing");
                return value == "1";
            }
        }

        /// <summary>
        /// 系统当前版本号
        /// </summary>
        public static string Version
        {
            get
            {
                string value = ReadConfigKey("version");
                return value;
            }
        }

        /// <summary>
        /// 读取配置文件的值 properties.config
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ReadConfigKey(string key)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "properties.config";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);

            string xpath = string.Format("/settings/add[@key='{0}']", key);
            XmlNode node = xmlDoc.SelectSingleNode(xpath);

            if (node != null)
                return node.Attributes["value"].Value;
            else
                return "";
        }

        /// <summary>
        /// 写入配置文件值 properties.config
        /// </summary>
        /// <param name="key"></param>
        /// <param name="?"></param>
        public static void WriteConfigKey(string key, string value)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "properties.config";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path);

            string xpath = string.Format("/settings/add[@key='{0}']", key);
            XmlNode node = xmlDoc.SelectSingleNode(xpath);
            node.Attributes["value"].Value = value;

            xmlDoc.Save(path);
        }

        #endregion
    }

    /// <summary>
    /// 当前操作者
    /// </summary>
    public class Operator
    {
        /// <summary>
        /// 操作者ID
        /// </summary>
        public int UserID { get; set; }

        /// <summary>
        /// 操作者姓名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 操作者手机
        /// </summary>
        public string MobileNo { get; set; }

        /// <summary>
        /// 所属公司
        /// </summary>
        public int CompanyID { get; set; }

        /// <summary>
        /// 所在公司名称
        /// </summary>
        public string CompanyName { get; set; }

        /// <summary>
        /// 公司分组
        /// </summary>
        public int CompanyCategoryID { get; set; }

        /// <summary>
        /// 当前操作者公司所属的上级公司
        /// </summary>
        public int ParentCompanyID { get; set; }

        /// <summary>
        /// 上级公司名称
        /// </summary>
        public string ParentCompanyName { get; set; }

        public DateTime LastLoginTime { get; set; }
    }

}
